package model

import (
    "gorm.io/gorm"
    "time"
    "yi-shou-backstage/util"
)

// 评论
type Comment struct {
    ID      int    `gorm:"primaryKey;comment:评论id" json:"id"`
    Content string `gorm:"type:varchar(1024);not null;comment:评论内容" json:"content,omitempty" validate:"required,omitempty" label:"评论内容"`
    Sticky  bool   `gorm:"type:bool;default:false;comment:是否置顶" json:"sticky,omitempty" validate:"omitempty" label:"是否置顶"`

    UserID int  `gorm:"type:int;not null;comment:用户id" json:"user_id,omitempty" validate:"required,omitempty" label:"用户id"`
    User   User `gorm:"foreignKey:UserID;constraint:OnUpdate:CASCADE" validate:"omitempty"`

    ArticleID int     `gorm:"type:int;not null;comment:文章id" json:"art_id,omitempty" validate:"required,omitempty" label:"文章id"`
    Article   Article `gorm:"foreignKey:ArticleID;constraint:OnUpdate:CASCADE"`

    ParentID int `gorm:"type:int;default=0;comment:父级评论id" json:"parent_id;omitempty" validate:"omitempty" label:"父级评论id"`

    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt gorm.DeletedAt `gorm:"index"`
}

func CreateComment(obj Comment) *Comment {
    err := db.Create(&obj).Error
    if err != nil {
        util.LogEntry.Errorf("Create comment failed, error = %s \n", err)
        return nil
    }
    return &obj
}

func UpdateCommentSticky(id int, obj Comment) *Comment {
    com := Comment{ID: id}
    err := db.Model(&com).Updates(map[string]interface{}{"sticky": obj.Sticky}).Error
    if err != nil {
        util.LogEntry.Errorf("Update comment sticky failed, error = %s \n", err)
        return nil
    }
    return &com
}
